<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 提收 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="active - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab栏切换   -->
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addRuleForm"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          v-model="active"
          :before-leave="beforeLeaveFn"
          @tab-click="tabClick"
        >
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateprops"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <!--  -->
            <el-form-item
              v-for="(item, index) in manyTable"
              :key="index"
              :label="item.attr_name"
            >
              <!-- 复选框组件的使用 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTable"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="headersObj"
              :on-success="headerSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <!-- 商品内容 -->
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addValidate">添加商品</el-button>
          </el-tab-pane>
          <!-- <el-tab-pane label="完成" name="5">定时任务补偿</el-tab-pane> -->
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog
      title="图片预览"
      :visible.sync="PicdialogVisible"
      width="70%"
      :before-close="handleClose"
    >
      <img :src="previewPic" alt="" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  data() {
    return {
      // 步骤条和tab栏数据联动
      active: "0",
      // 添加表单数据对象
      addForm: {
        goods_name: "",
        goods_price: "",
        goods_weight: "",
        goods_number: "",
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: [],
      },
      // 添加表单验证规则
      addRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
        // pics: [{ required: true, message: "请选择商品分类", trigger: "blur" }],
      },
      // 保存分类商品数据
      cateList: [],
      cateprops: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 保存动态参数
      manyTable: [],
      onlyTable: [],
      // 图片地址
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      // 设置header请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      previewPic: "",
      PicdialogVisible: false,
    };
  },
  created() {
    this.getCate();
  },

  methods: {
    // 获取商品分类数据
    async getCate() {
      const { data: res } = await this.$axios.get("categories");
      if (res.meta.status !== 200) return this.$message.error("获取失败");
      this.cateList = res.data;
      // console.log(this.cateList);
    },
    // 联机选择器绑定的change事件
    handleChange() {
      // 必须选择联级选择去的第三级
      if (this.addForm.goods_cat.length !== 3)
        return (this.addForm.goods_cat = []);
    },
    // tab栏切换
    beforeLeaveFn(activeName, oldactiveName) {
      /* 
          oldactiveName === "0" tab栏name绑定的值
          this.addForm.goods_cat.length !== 3 联级选择器必须是第三级
      */
      if (oldactiveName === "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.info("请选择商品分类");
        return false;
      }
    },
    // tab栏点击，进行获取数据
    async tabClick() {
      // 访问商品参数
      if (this.active === "1") {
        const { data: res } = await this.$axios.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "many" },
          }
        );

        if (res.meta.status !== 200)
          return this.$message.error("获取动态参数失败");
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
        });
        this.manyTable = res.data;
        // console.log(this.manyTable);
      } else if (this.active === "2") {
        //访问商品属性
        const { data: res } = await this.$axios.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "only" },
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error("获取静态属性失败");
        this.onlyTable = res.data;
        // console.log(this.onlyTable);
      }
    },
    // 图片预览
    handlePreview(file) {
      /* 
         1. file.response.data.url 保存的绝对路径
         2.图片预览对话框显示
      */
      this.previewPic = file.response.data.url;
      this.PicdialogVisible = true;
    },
    // 关闭图片预览对话框
    handleClose() {
      // 图片清空 对话框关闭
      this.previewPic = "";
      this.PicdialogVisible = false;
    },
    // 移除图片
    handleRemove(file) {
      /*  1.获取图片的临时路径
          2.通过findIndex查询对应对象的索引值
          3.splice删除pics对象的值
      */
      const filePath = file.response.data.tmp_path;
      const ind = this.addForm.pics.findIndex((item) => item.pic === filePath);
      this.addForm.pics.splice(ind, 1);
      // console.log(this.addForm);
    },
    // 图片上传成功的
    headerSuccess(response) {
      /* 
         1.拼接图片的临时路径
         2.将拼接的值添加到对应的数组中
      */
      const picsInfo = {
        pic: response.data.tmp_path,
      };

      this.addForm.pics.push(picsInfo);
      // console.log(this.addForm);
    },
    // 添加商品
    addValidate() {
      this.$refs.addRuleForm.validate(async (valid) => {
        if (!valid) return this.$message.error("数据不合法");
        /* goods_cat的处理，接口文档中是字符串，所以要进行转换 === 但是在当前商品中，在表单中进行绑定 so？ 如何处理？ */
        /* 
         1.使用ladash插件，
         2.cloneDeep进行深拷贝
         3.使用join转化字符串
        */
        const Form = _.cloneDeep(this.addForm);
        Form.goods_cat = Form.goods_cat.join(",");
        // 处理动态参数
        this.manyTable.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" "),
          };
          this.addForm.attrs.push(newInfo);
        });
        // 处理静态属性
        this.onlyTable.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          this.addForm.attrs.push(newInfo)
        });
        Form.attrs = this.addForm.attrs
        // console.log(Form);
        // 发送添加商品的请求
        const { data: res } = await this.$axios.post("goods", Form);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success("添加商品成功");
        // 跳转goods页面 
        this.$router.push('/goods')
      });
    },
  },
  computed: {
    // 保存添加商品所选的ID
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
      return null;
    },
  },
};
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 20px 5px 0 !important;
}
.el-button {
  margin-top: 15px;
}
</style>